import 'dart:io';
import 'dart:math';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '文件批量重命名字',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var rootPath = '';
  var editFileType = '.mp4';
  var replaceFrom = '';
  var replaceText = '';
  int minLength = 0;
  int addNumber = 0;
  var musicMode = false;
  final controller = TextEditingController(text: '.mp4');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            Row(
              children: [
                Text(rootPath),
                TextButton(
                    onPressed: () async {
                      final path = await FilePicker.platform.getDirectoryPath();
                      if (path != null) {
                        rootPath = path;
                        change();
                      }
                    },
                    child: const Text('选择文件路径')),
                TextButton(
                    onPressed: () async {
                      setState(() {
                        musicMode = !musicMode;
                      });
                    },
                    child: Text(musicMode?'音频模式':'自定义模式')),

                TextButton(
                    onPressed: () async {
                      final tip = musicLrcExists();
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(tip??'都存在')));
                    },
                    child: const Text('歌词存在验证')),

                TextButton(
                    onPressed: () async {
                      if (rootPath.isNotEmpty) {
                        final files = Directory(rootPath).listSync();
                        final size = files.length.toString().length;
                        for (var element in files) {
                          if (element is File) {
                            if (editFileType.isEmpty ||
                                path.extension(element.path).toLowerCase() ==
                                    editFileType) {
                              final name = path.basename(element.path);
                              final newName = newFileName(name, size);
                              if (newName != name) {
                                element.renameSync(rootPath +
                                    Platform.pathSeparator +
                                    newName);
                              }
                            }
                          }
                        }
                        setState(() {});
                      }
                    },
                    child: const Text('确定修改'))
              ],
            ),
            TextField(
              controller: controller,
              decoration: const InputDecoration(
                  labelText: '修改的文件后缀', hintText: '如：.mp4'),
              onChanged: (text) {
                editFileType = text;
                change();
              },
            ),
            TextField(
              decoration: const InputDecoration(
                labelText: '替换前的文本',
              ),
              onChanged: (text) {
                replaceFrom = text;
                change();
              },
            ),
            TextField(
              decoration: const InputDecoration(
                labelText: '替换后的文本',
              ),
              onChanged: (text) {
                replaceText = text;
                change();
              },
            ),
            TextField(
              decoration: const InputDecoration(
                  labelText: '最少长度，前面自动补0', hintText: '默认为文件数量自适应'),
              onChanged: (text) {
                try {
                  minLength = int.parse(text);
                } catch (e) {
                  minLength = 0;
                }
                change();
              },
            ),
            TextField(
              decoration: const InputDecoration(
                labelText: '数字增加',
              ),
              onChanged: (text) {
                try {
                  addNumber = int.parse(text);
                } catch (e) {
                  addNumber = 0;
                }
                change();
              },
            ),
            ...preNames(),
          ],
        ),
      ),
    );
  }

  List<Widget> preNames() {
    final list = <Widget>[];
    if (rootPath.isNotEmpty) {
      final files = Directory(rootPath).listSync();
      files.sort((a, b) => path
          .basename(a.path)
          .toLowerCase()
          .compareTo(path.basename(b.path).toLowerCase()));
      final size = files.length.toString().length;
      for (var element in files) {
        if (element is File) {
          if (editFileType.isEmpty ||
              path.extension(element.path).toLowerCase() == editFileType) {
            final name = path.basename(element.path);
            list.add(Text('$name -> ${newFileName(name, size)}'));
          }
        }
      }
    }
    return list;
  }

  String? musicLrcExists(){
    final files = Directory(rootPath).listSync();
    for (var element in files) {
      if (element is File) {
        if (path.extension(element.path).toLowerCase() == '.mp3') {
          final name = path.basename(element.path);
          if(!File(element.path.replaceAll('.mp3', '.lrc')).existsSync()){
            return name;
          }
        }
      }
    }
    return null;
  }

  String newFileName(String oldName, int size) {
    if(musicMode){
      return musicFileName(oldName);
    }
    var newName = oldName;
    newName = newName.substring(0, newName.length - editFileType.length);

    if (replaceFrom.isNotEmpty) {
      if (replaceFrom.contains('*')) {
        final starSplits = replaceFrom.split('*');
        final start = max(0, newName.indexOf(starSplits.first));
        final end = max(start, newName.indexOf(starSplits.last, start)) +
            starSplits.last.length;
        newName = newName.replaceRange(start, end, replaceText);
        newName = newName.split('_').first.trim();
      } else {
        newName = newName.replaceAll(replaceFrom, replaceText);
        newName = newName.split('_').first.trim();
      }
    }

    try {
      final number = int.parse(newName);
      newName = (number + addNumber).toString();
      final length = max(size, minLength);
      while (newName.length < length) {
        newName = '0$newName';
      }
    } catch (_) {
      try {
        final splits = newName.split(' ');
        var isFirst = true;
        for (var c in splits) {
          if (isFirst) {
            isFirst = false;
            final number = int.parse(c);
            newName = (number + addNumber).toString();
            final length = max(size, minLength);
            while (newName.length < length) {
              newName = '0$newName';
            }
          } else {
            newName += ' $c';
          }
        }
      } catch (_) {}
    }

    return newName + editFileType;
  }

  String musicFileName(String oldName) {
    var newName = oldName.substring(0, oldName.length - editFileType.length).replaceAll('&', ',');
    if (newName.contains('-')) {
      final nameSplit = newName.split('-');
      newName = '${nameSplit.first.trim()} - ${nameSplit.last.trim()}';
    }
    return newName + editFileType;
  }

  void change() {
    setState(() {});
  }
}
